package com.example.docking.httpCRM.httpSend;

import com.example.docking.httpCRM.dao.GenericResponse;
import com.example.docking.httpCRM.dao.LoginInfo;
import com.example.docking.httpCRM.dao.LoginRetData;
import com.example.docking.httpCRM.dao.RequestBodyParam;
import com.example.docking.httpCRM.util.CRM_MD5;
import com.example.docking.httpCRM.util.Constants;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import okhttp3.*;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

public class XToolsCRMLoginAPI {
    private static final OkHttpClient client = new OkHttpClient();
    private static final Gson gson = new Gson();
    private static final ConcurrentHashMap<String, String> cache = new ConcurrentHashMap<>();

    public static GenericResponse<LoginRetData> login(String cmd, String appid, String appkey, String comkeyid, String com, String part) throws IOException {
        String stamp = String.valueOf(System.currentTimeMillis() / 1000);

        // 生成 upr 中的 md
        String uprMdInput = stamp + comkeyid + com + part;
        CRM_MD5 md5 = new CRM_MD5();
        String uprMd = md5.generateMD5(uprMdInput);

        LoginInfo upr = new LoginInfo(comkeyid, com, part, uprMd);

        // 生成参数 md
        String mdInput = "[]" + stamp + gson.toJson(upr) + cmd + appkey;
        String md = md5.generateMD5(mdInput);

        RequestBodyParam param = new RequestBodyParam(cmd, appid, stamp, upr, md);
        String json = gson.toJson(param);

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request = new Request.Builder()
                .url(Constants.LOGIN_API_URL)
                .post(requestBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            String responseBodyString = Objects.requireNonNull(response.body()).string();
            GenericResponse<LoginRetData> responseObject = gson.fromJson(responseBodyString, new TypeToken<GenericResponse<LoginRetData>>() {
            }.getType());
            return responseObject;
        }
    }

    public String loginGetSid() {
        // 示例参数，需替换为真实值
        String cmd = "user.login";
        String appid = "open00001_sajdjsjsj";
        String appkey = "open1slslslsdldlsdlds";
        String comkeyid = "xtoolsplusd002";
        String com = "d002";
        String part = "";
        String sid = "";
        try {
            GenericResponse<LoginRetData> response = login(cmd, appid, appkey, comkeyid, com, part);
            if (response.getOk() == 1) {
                LoginRetData retData = response.getRet();
                sid = retData.getSid();
                System.out.println("登录成功，SID: " + sid);
                // 将 SID 存入缓存
                cache.put("sid", sid);
            } else {
                System.out.println("登录失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sid;
    }

    public static void main(String[] args) {
        XToolsCRMLoginAPI service = new XToolsCRMLoginAPI();
        service.loginGetSid();
        // 从缓存中获取 SID
        String sidFromCache = cache.get("sid");
        System.out.println("从缓存中获取的 SID: " + sidFromCache);
    }
}
